<template>
  <div class="visit-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>就诊管理</el-breadcrumb-item>
      <el-breadcrumb-item>就诊</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <div class="patientList-title">
        患者列表
      </div>
      <div class="optionBtn-wrapper">
        <el-button
            @click="handleCall"
            size="mini"
            type="primary">
          叫号
        </el-button>
        <el-button
            @click="handleVisit"
            size="mini"
            type="success">
          就诊
        </el-button>
        <el-button
            @click="handleOvertime"
            size="mini"
            type="danger">
          过号
        </el-button>
      </div>
      <el-col :span="6">
        <el-table
            ref="patientTable"
            highlight-current-row
            @current-change="handleCurrentChange"
            class="patientList-wrapper"
            max-height="300"
            :data="patientList"
            style="width: 100%">
          <el-table-column
              type="index"
              width="40">
          </el-table-column>
          <el-table-column
              prop="cardNo"
              label="卡号"
              width="100">
          </el-table-column>
          <el-table-column
              prop="name"
              label="姓名"
              width="100">
          </el-table-column>
          <el-table-column
              label="状态"
              width="80">
            <template slot-scope="scope">
              {{scope.row.params.overtime==0?'待就诊':'已超时'}}
            </template>
          </el-table-column>
        </el-table>

        <div class="overtime-patient-title">过号患者</div>
        <!--过号患者列表-->
        <el-table
            ref="overtimePatientTable"
            highlight-current-row
            @current-change="handleOvertimeCurrentChange"
            class="patientList-wrapper"
            max-height="300"
            :data="overtimePatientList"
            style="width: 100%">
          <el-table-column
              type="index"
              width="40">
          </el-table-column>
          <el-table-column
              prop="cardNo"
              label="卡号"
              width="100">
          </el-table-column>
          <el-table-column
              prop="name"
              label="姓名"
              width="100">
          </el-table-column>
          <el-table-column
              label="状态"
              width="80">
              已超时
          </el-table-column>
        </el-table>
        <div class="patient-info-wrapper">
          <el-descriptions class="margin-top" title="患者信息" :column="3" size="medium" border v-if="patient!=null">
            <el-descriptions-item>
              <template slot="label">
                姓名
              </template>
              {{patient.name}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                手机
              </template>
              {{patient.phone}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                性别
              </template>
                {{patient.sex==0?'男':'女'}}
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                住址
              </template>
               {{patient.address}}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="overtime-patient-title">历史就诊记录</div>
        <!--历史就诊记录列表-->
        <el-table
            class="pastPrescription-wrapper"
            max-height="300"
            highlight-current-row
            @current-change="handleCurrentPastPrescriptionChange"
            :data="pastPrescriptionList"
            style="width: 100%">
          <el-table-column
              type="index"
              width="40">
          </el-table-column>
          <el-table-column
              prop="params.docname"
              label="医生"
              width="100">
          </el-table-column>
          <el-table-column
              prop="params.depname"
              label="科室"
              width="100">
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="日期"
              width="90">
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="18">
        <div class="tabs-wrapper">
          <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
            <el-tab-pane label="问诊" name="first">
              <el-form :inline="true" :model="prescription" class="demo-form-inline" label-width="80px">
                <el-form-item label="体温">
                  <el-input style="width: 60px" v-model="prescription.temperature" placeholder="体温"></el-input> °C
                </el-form-item>
                <el-form-item label="脉搏">
                  <el-input style="width: 60px" v-model="prescription.pluse" placeholder="脉搏"></el-input> bpm
                </el-form-item>
                <el-form-item label="心率">
                  <el-input style="width: 60px" v-model="prescription.heartRate" placeholder="心率"></el-input> 次/分钟
                </el-form-item>
                <el-form-item label="血压">
                  <el-input style="width: 60px" v-model="prescription.bloodPressure" placeholder="血压"></el-input> mmHg
                </el-form-item>
              </el-form>
              <el-form ref="form" :model="prescription" label-width="80px">
                <el-form-item label="主诉" >
                  <el-input type="textarea" :rows="5" v-model="prescription.chiefComplaint"></el-input>
                </el-form-item>
                <el-form-item label="个人史">
                  <el-input type="textarea" :rows="5" v-model="prescription.personalHistory"></el-input>
                </el-form-item>
                <el-form-item label="既往史">
                  <el-input type="textarea" :rows="5" v-model="prescription.pastHistory"></el-input>
                </el-form-item>
                <el-form-item label="体查">
                  <el-input type="textarea" :rows="5" v-model="prescription.bodyCheck"></el-input>
                </el-form-item>
                <el-form-item label="初步诊断">
                  <el-input v-model="prescription.initialDiagnosis" :rows="5"></el-input>
                </el-form-item>
                <el-form-item label="其他意见或建议">
                  <el-input v-model="prescription.advice" :rows="5"></el-input>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="用药" name="second">
              <div class="second-wrapper">
                <div class="add-medicine-wrapper">
                  <el-row>
                    <el-col :span="3" style="line-height: 40px">处方（+R）</el-col>
                    <el-col :span="2">
                      <el-button type="primary" @click="handleDeleteMedCineDetail">删除</el-button>
                    </el-col>
                    <el-col :span="18">
                      <el-button plain @click="handleClearMedicineDetail">清空</el-button>
                    </el-col>
                  </el-row>

                  <el-table
                      :header-cell-style="{ background: '#f3f6fd', color: '#555' }"
                      :data="prescriptionMedicineList"
                      max-height="250"
                      border
                      style="width: 100%">
                    <el-table-column
                        prop="id"
                        label="编号"
                        width="180">
                    </el-table-column>
                    <el-table-column
                        prop="medName"
                        label="药品名称"
                        width="180">
                    </el-table-column>
                    <el-table-column
                        prop="specifications"
                        label="规格">
                    </el-table-column>
                    <el-table-column
                        prop="consumption"
                        label="用量">
                      <template slot-scope="scope">
                        <el-input v-model="prescriptionMedicineList[scope.$index].consumption" placeholder="用量"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="数量">
                      <template slot-scope="scope">
                        <el-input-number v-model="prescriptionMedicineList[scope.$index].amount" :key="inputKey" @change="handleAmountChange()" :min="1" :max="10" label="数量"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column
                        label="操作">
                      <template slot-scope="scope">
                        <el-button type="primary" size="small" @click="handleDeleteMedCineDetail(scope.$index)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>


                <el-row>
                  <el-col :span="3" style="line-height: 40px">药品查询</el-col>
                  <el-col :span="21">
                    <el-form :inline="true" :model="searchObj" class="demo-form-inline">
                      <el-form-item>
                        <el-input v-model="searchObj.medName" placeholder="输入药品名进行查询"></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="handleSearchMedicine" icon="el-icon-search">查询</el-button>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="success" @click="handleAddMedicine">添加</el-button>
                      </el-form-item>
                    </el-form>
                  </el-col>
                  <el-table
                      highlight-current-row
                      @current-change="handleMedicineCurrentChange"
                      :header-cell-style="{ background: '#f3f6fd', color: '#555' }"
                      :data="medicineList"
                      max-height="250"
                      border
                      style="width: 100%">
                    <el-table-column
                        prop="id"
                        label="编号"
                        width="180">
                    </el-table-column>
                    <el-table-column
                        prop="medName"
                        label="药品名称"
                        width="180">
                    </el-table-column>
                    <el-table-column
                        prop="specifications"
                        label="规格">
                    </el-table-column>
                    <el-table-column
                        prop="factory"
                        label="厂家">
                    </el-table-column>
                  </el-table>
                </el-row>

              </div>
            </el-tab-pane>
            <el-tab-pane label="处方" name="third">
              <div class="prescriptionBtn-wrapper">
                <el-row>
                  <el-button type="primary" size="mini" @click="handleSendPrescription">发送处方</el-button>
                </el-row>
              </div>

              <div class="prescription-wrapper" v-if="patient">
                <div class="prescription-title">
                  普通处方笺
                </div>
                <div class="prescription-patient-info">
                  <el-descriptions>
                    <el-descriptions-item label="姓名">{{patient.name}}</el-descriptions-item>
                    <el-descriptions-item label="性别">
                      <span v-if="patient.sex!=null">{{patient.sex==0?'男':'女'}}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="年龄">{{patient.age}}</el-descriptions-item>
                    <el-descriptions-item label="诊断">
                      {{prescription.initialDiagnosis}}
                    </el-descriptions-item>
                    <el-descriptions-item label="日期">{{new Date()}}</el-descriptions-item>
                  </el-descriptions>
                </div>
                <div class="disease-description">
                  <el-descriptions class="margin-top" :column="1">
                    <el-descriptions-item label="主诉">{{prescription.chiefComplaint}}</el-descriptions-item>
                    <el-descriptions-item label="个人史">{{prescription.personalHistory}}</el-descriptions-item>
                    <el-descriptions-item label="既往史">{{prescription.pastHistory}}</el-descriptions-item>
                    <el-descriptions-item label="体查">
                      {{prescription.bodyCheck}}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>
                <div class="doctor-advice">
                  <el-descriptions class="" :column="1" direction="vertical">
                    <el-descriptions-item label="医嘱">
                      <el-table
                          :header-cell-style="{ background: '#f3f6fd', color: '#555' }"
                          :data="prescriptionMedicineList"
                          max-height="250"
                          border
                          style="width: 100%">
                        <el-table-column
                            prop="medName"
                            label="药品名称"
                            width="180">
                        </el-table-column>
                        <el-table-column
                            prop="specifications"
                            label="规格">
                        </el-table-column>
                        <el-table-column
                            prop="consumption"
                            label="用量">
                          <template slot-scope="scope">
                            <span>{{prescriptionMedicineList[scope.$index].consumption}}</span>
                          </template>
                        </el-table-column>
                        <el-table-column
                            label="数量">
                          <template slot-scope="scope">
                            <span>{{prescriptionMedicineList[scope.$index].amount}}</span>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-descriptions-item>
                  </el-descriptions>
                  <el-descriptions class="margin-top" :column="1">
                    <el-descriptions-item label="其他意见或建议">{{prescription.advice}}</el-descriptions-item>
                  </el-descriptions>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>

    <el-dialog
        class="prescription-detail-dialog-wrapper"
        title="处方信息"
        :visible.sync="dialogVisible"
        width="50%"
        >
      <div v-if="patient" class="prescription-wrapper">
        <div class="prescription-title">
          普通处方笺
        </div>
        <div class="prescription-patient-info">
          <el-descriptions>
            <el-descriptions-item label="姓名">{{patient.name}}</el-descriptions-item>
            <el-descriptions-item label="性别">
              <span v-if="patient.sex!=null">{{patient.sex==0?'男':'女'}}</span>
            </el-descriptions-item>
            <el-descriptions-item label="年龄">{{patient.age}}</el-descriptions-item>
            <el-descriptions-item label="诊断">
              {{selectPastPrescription.initialDiagnosis}}
            </el-descriptions-item>
            <el-descriptions-item label="日期">{{selectPastPrescription.createTime}}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="disease-description">
          <el-descriptions class="margin-top" :column="1">
            <el-descriptions-item label="主诉">{{selectPastPrescription.chiefComplaint}}</el-descriptions-item>
            <el-descriptions-item label="个人史">{{selectPastPrescription.personalHistory}}</el-descriptions-item>
            <el-descriptions-item label="既往史">{{selectPastPrescription.pastHistory}}</el-descriptions-item>
            <el-descriptions-item label="体查">
              {{selectPastPrescription.bodyCheck}}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="doctor-advice">
          <el-descriptions class="" :column="1" direction="vertical">
            <el-descriptions-item label="医嘱">
              <el-table
                  :header-cell-style="{ background: '#f3f6fd', color: '#555' }"
                  :data="pastPrescriptionDetailList"
                  max-height="250"
                  border
                  style="width: 100%">
                <el-table-column
                    prop="params.medName"
                    label="药品名称"
                    width="180">
                </el-table-column>
                <el-table-column
                    prop="specifications"
                    label="规格">
                </el-table-column>
                <el-table-column
                    prop="consumption"
                    label="用量">
                </el-table-column>
                <el-table-column
                    label="数量">
                </el-table-column>
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
          <el-descriptions class="margin-top" :column="1">
            <el-descriptions-item label="其他意见或建议">{{selectPastPrescription.advice}}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div >
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from "vuex";
import doctorApi from "@/api/doctor";
import patientApi from "@/api/patient";
import medicineApi from "@/api/medicine";
import prescriptionApi from "@/api/prescription";

export default {
  name:'VisitIndex',
  data() {
    return {
      docId:'',
      activeName:'third',
      inputKey:false,
      dialogVisible:false,
      patientSelect:false,
      overtimePatientSelect:false,
      currentPatRow:null,
      socket:null,
      searchObj: {},
      currentMedicineRow:{},
      patient:{name:''},
      doctor:{},
      prescriptionSearchObj:{},
      prescription:{},
      selectPastPrescription:{},
      form:{},
      patientList:[],
      overtimePatientList:[],
      medicineList:[],
      prescriptionMedicineList:[],
      prescriptionDetailList:[],
      pastPrescriptionList:[],
      pastPrescriptionDetailList:[],
    }
  },
  created() {
    this.init()
  },
  computed:{
    ...mapState(['user'])
  },
  destroyed() {
    this.socket.close() //离开路由之后断开websocket连接
  },
  methods: {
    async init(){
      const{data:resp} = await doctorApi.isAuth()
      if (!resp.data){
        return this.$message({type:'error',duration:1000,message:'尚未通过认证，请联系管理员',onClose:()=>{
          this.$router.go(-1)
          }})
      }
      const userId = this.user.userId
      const {data:res} = await doctorApi.findByUserId(userId)
      this.doctor = res.data
      this.docId = res.data.id
      //获取患者列表
      await this.getPatientList()
      await this.getVisitPatient()
      //建立websocket连接
      this.socket = new WebSocket(`ws://localhost:8080/ws/doctor/${this.docId}`)
      this.socket.onmessage = this.websocketonmessage;
      this.socket.onopen = this.websocketonopen;
      this.socket.onerror = this.websocketonerror;
      this.socket.onclose = this.websocketclose;
    },
    websocketonmessage(e){
      console.log(e)
      const msg = JSON.parse(e.data)
      switch (msg.action){
        case 'updatePatList':{
          this.getPatientList(this.docId)
          return
        }
        default:return
      }
    },
    websocketonopen(){

    },
    websocketonerror(){

    },
    websocketclose(){

    },
    //查询药品
    async handleSearchMedicine() {
      const {data:res} = await medicineApi.findWithNoPage(this.searchObj)
      this.medicineList = res.data
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    handleCall(){
      if (this.currentPatRow==null){
        return this.$message({
          message: '请先选择患者信息',
          type: 'warning'
        });
      }

      //向叫号端发送叫号请求
      const action = 'notifyPatient'
      const receiverDepcode = this.doctor.depcode
      const params = {'name':this.currentPatRow.name,docId:this.doctor.id}
      const msg = {action,receiverDepcode,params}
      console.log(JSON.stringify(msg))
      this.socket.send(JSON.stringify(msg))
    },
   async handleVisit(){
      if (this.currentPatRow==null){
        return this.$message({
          message: '请先选择患者信息',
          type: 'warning'
        });
      }

      //判断是过号患者的就诊还是排队队列的就诊
      let type
      if (this.patientSelect){
        type=0
      }else{
        type=1
      }

     const {data:res} = await patientApi.patientVisit(type,this.currentPatRow.params.orderInfoId,this.docId)
     if (res.data==true){
       //设置病人的信息
       this.patient = this.currentPatRow

       //更新患者列表信息
       await this.getPatientList()

       //向叫号端发送更新患者列表请求
       const action = 'updatePatientToNotify'
       const receiverDepcode = this.doctor.depcode
       const msg = {action,receiverDepcode}
       this.socket.send(JSON.stringify(msg))
     }else{
       return this.$message({
         message: '请就诊完上一个患者！',
         type: 'warning'
       });
     }
    },
    async handleOvertime(){
      if (this.overtimePatientSelect){
        return this.$message({
          message: '不能将患者再次过号',
          type: 'warning'
        });
      }

      if (this.currentPatRow==null){
        return this.$message({
          message: '请先选择患者信息',
          type: 'warning'
        });
      }

      const {data:res} = await patientApi.patientOvertime(this.currentPatRow.params.orderInfoId,this.docId)
      if (res.data==true){
        //更新患者列表
        await this.getPatientList()

        //向叫号端发送更新患者列表请求
        const action = 'updatePatientToNotify'
        const receiverDepcode = this.doctor.depcode
        const msg = {action,receiverDepcode}
        this.socket.send(JSON.stringify(msg))
      }else{
        return this.$message({
          message: '过号失败',
          type: 'warning'
        });
      }
    },
    handleCurrentChange(currentRow, oldCurrentRow){
      if (this.overtimePatientSelect){
        this.$refs.overtimePatientTable.setCurrentRow();
      }
      this.currentPatRow = currentRow
      this.patientSelect=true
      this.overtimePatientSelect=false
    },
    handleOvertimeCurrentChange(currentRow, oldCurrentRow){
      if (this.patientSelect){
        this.$refs.patientTable.setCurrentRow();
      }
      this.currentPatRow = currentRow
      this.overtimePatientSelect=true
      this.patientSelect=false
    },
    async getPatientList(){
      const{data:res} = await patientApi.getPatientList(this.docId)
      this.patientList = res.data

      const{data:resp} = await patientApi.getOvertimePatient(this.docId)
      this.overtimePatientList = resp.data
    },
    async getVisitPatient(){
      const{data:res} = await patientApi.getVisitPatient(this.docId)
      this.patient = res.data
      if (this.patient){
        await this.getPastPrescriptionList()
      }
    },
    async getPastPrescriptionList(){
      this.prescriptionSearchObj.cardNo = this.patient.cardNo
      const {data:res} = await prescriptionApi.getPastPrescriptionList(this.prescriptionSearchObj);
      this.pastPrescriptionList = res.data
    },
    handleMedicineCurrentChange(currentRow, oldCurrentRow){
      this.currentMedicineRow = currentRow
    },
    handleAddMedicine(){
      if (this.currentMedicineRow.id==null){
        return this.$message({
          message: '请先选择一条药品信息',
          type: 'warning'
        });
      }

      let flag = true;

      for(let i=0;i<this.prescriptionMedicineList.length;i++){
        if (this.prescriptionMedicineList[i].id==this.currentMedicineRow.id){
          this.prescriptionMedicineList[i].amount++
          flag = false
          break
        }
      }

      if (flag){
        this.currentMedicineRow.amount=1
        this.prescriptionMedicineList.push(this.currentMedicineRow)
      }
      this.inputKey = !this.inputKey
    },
    handleAmountChange(value){
      console.log(value)
    },
    async handleSendPrescription(){
      const confirmResult =await this.$confirm('请再次确认处方内容?', '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err=>err)
      // catch是为了把取消报错组成返回值err
      if(confirmResult!='confirm'){
        return this.$message.info('已取消发送')
      }

      //todo 发送处方前判断参数格式

      //设置参数的其他值和格式
      this.prescription.orderInfoId = this.patient.params.orderInfoId
      this.prescription.cardNo = this.patient.cardNo
      this.prescription.docId = this.doctor.id
      this.prescriptionMedicineList.forEach(item=>{
        const prescriptionDetail = {medId:item.id,amount:item.amount,consumption:item.consumption}
        this.prescriptionDetailList.push(prescriptionDetail)
      })
      //调用api方法
      const{data:res} =await prescriptionApi.generate(this.prescription,this.prescriptionDetailList)

      //清空处方信息
      if (res.data==true){
        this.prescription = {}
        this.prescriptionMedicineList=[]
        this.prescriptionDetailList=[]
        this.patient={}
        this.pastPrescriptionList = []
      }

      //更新病人信息
      await this.getPatientList()

      //向叫号端发送更新病人请求
      const action = 'updatePatientToNotify'
      const receiverDepcode = this.doctor.depcode
      const msg = {action,receiverDepcode}
      this.socket.send(JSON.stringify(msg))
    },
    handleClearMedicineDetail(){
      this.prescriptionMedicineList = []
    },
    handleDeleteMedCineDetail(index){
      this.prescriptionMedicineList.splice(index,1)
    },
    async handleCurrentPastPrescriptionChange(currentRow, oldCurrentRow){
      this.selectPastPrescription = currentRow
      const {data:res} = await prescriptionApi.getPastPrescriptionDetail(currentRow.id)
      this.pastPrescriptionDetailList = res.data
      this.dialogVisible = true
    },
    handleClose(){

    }
  },
}
</script>
<style scoped lang="less">
.visit-container{
  .patientList-title{
    font-size: 16px;
    font-weight: 700;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 10px;
  }
  .optionBtn-wrapper{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 10px;
    padding-left: 10px;
  }
  .patientList-wrapper{
    margin-bottom: 20px;
  }
  .pastPrescription-wrapper{
    margin-bottom: 20px;
  }
  .overtime-patient-title{
    font-size: 16px;
    font-weight: 700;
  }
  .patient-info-wrapper{
    .el-descriptions__header{
      margin-bottom: 0!important;
    }
    margin-bottom: 20px;
  }
  .tabs-wrapper{
    margin-top: 15px;
    .second-wrapper{
      border: 1px #f3f6fd solid;
      .add-medicine-wrapper{
        margin-bottom: 10px;
      }
    }
    .prescription-wrapper{
      border-bottom: solid 2px black;
      height: auto;
      width: 700px;
      margin: 0 auto;
      .prescription-title{
        text-align: center;
        font-size: 24px;
        font-weight: bold;
        letter-spacing:5px;
        padding-bottom: 10px;
      }
      .prescription-patient-info{
        border-bottom: solid 2px black;
        margin-bottom: 10px;
      }
    }
  }
  .prescription-detail-dialog-wrapper{
    .prescription-wrapper{
      border-bottom: solid 2px black;
      height: auto;
      width: 700px;
      margin: 0 auto;
      .prescription-title{
        text-align: center;
        font-size: 24px;
        font-weight: bold;
        letter-spacing:5px;
        padding-bottom: 10px;
      }
      .prescription-patient-info{
        border-bottom: solid 2px black;
        margin-bottom: 10px;
      }
    }
  }
}
</style>